﻿using OfficeOpenXml;
using Stock_App.Enties;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Stock_App_V1
{
    /// <summary>
    /// StockPage.xaml 的交互逻辑
    /// </summary>
    public partial class StockPage : Page, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private string _searchText;
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    OnPropertyChanged(nameof(SearchText));
                }
            }
        }

        private DateTime _startDate;
        public DateTime StartDate
        {
            get { return _startDate; }
            set
            {
                if (_startDate != value)
                {
                    _startDate = value;
                    OnPropertyChanged(nameof(StartDate));
                }
            }
        }

        private DateTime _endDate;
        public DateTime EndDate
        {
            get { return _endDate; }
            set
            {
                if (_endDate != value)
                {
                    _endDate = value;
                    OnPropertyChanged(nameof(EndDate));
                }
            }
        }
        private ObservableCollection<StockDataShow> _stockItems = new ObservableCollection<StockDataShow>();
        public ObservableCollection<StockDataShow> StockItems
        {
            get { return _stockItems; }
            set
            {
                if (_stockItems != value)
                {
                    _stockItems = value;
                    OnPropertyChanged(nameof(StockItems));
                }
            }
        }
        public StockPage()
        {
            InitializeComponent();
            DataContext = this; // 确保 DataContext 被设置为当前的视图模型
            StartDate = DateTime.Today.AddDays(-7);
            EndDate = DateTime.Today.AddDays(1);
            StockItems = new ObservableCollection<StockDataShow>();
        }

        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            SearchText = SearchTextBox.Text;
        }
        private async Task SearchAsync()
        {
            StockItems.Clear();
            stockshManager stockshManager = new stockshManager();
            stockszManager stockszManager = new stockszManager();
            DateTime startTime = StartDate;
            DateTime endTime = EndDate;
            var filteredDatash =  stockshManager.GetListSD(startTime, endTime, SearchText);
            var filteredDatasz = stockszManager.GetListSD(startTime, endTime, SearchText);
            foreach (var item in filteredDatash)
            {
                StockItems.Add(item);
            }
            foreach (var item in filteredDatasz)
            {
                StockItems.Add(item);
            }
        }
        private async void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            await SearchAsync();
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (_stockItems == null || _stockItems.Count == 0)
            {
                MessageBox.Show("没有要保存的数据。");
                return;
            }

            // 创建一个SaveFileDialog实例  
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();

            // 设置默认文件名，包含当前日期（假设使用年月日格式）  
            string defaultFileName = $"MyExcelFile_{DateTime.Now:yyyyMMdd}.xlsx";
            saveFileDialog.FileName = defaultFileName;

            // 设置默认文件类型过滤器  
            saveFileDialog.DefaultExt = "xlsx";
            saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            // 显示对话框  
            bool? result = saveFileDialog.ShowDialog();

            // 检查用户是否点击了“保存”按钮  
            if (result == true)
            {
                // 获取用户选定的文件名  
                string fileName = saveFileDialog.FileName;

                // 直接使用用户选定的文件名，不强制添加日期（如果需要，可以在UI层面提示用户）  
                ExportListToExcel(StockItems.ToList(), fileName);

                // 显示消息框通知用户文件已保存  
                MessageBox.Show($"文件已保存为: {fileName}");
            }

        }


        public void ExportListToExcel<T>(List<T> data, string filePath)
        {
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial; // 设置许可证上下文  

            var fileInfo = new FileInfo(filePath);

            using (var package = new ExcelPackage(fileInfo))
            {
                var ws = package.Workbook.Worksheets.Add("Sheet1");

                // 获取T的属性信息  
                var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                // 写入标题行  
                for (int col = 1; col <= properties.Length; col++)
                {
                    ws.Cells[1, col].Value = properties[col - 1].Name;
                }

                // 写入数据行  
                int row = 2;
                foreach (var item in data)
                {
                    for (int col = 1; col <= properties.Length; col++)
                    {
                        var prop = properties[col - 1];
                        ws.Cells[row, col].Value = prop.GetValue(item, null) ?? ""; // 使用null合并运算符来处理null值  
                    }
                    row++;
                }

                // 自动调整列宽（可选）  
                ws.Cells.AutoFitColumns();

                // 保存Excel文件  
                package.Save();
            }

            Console.WriteLine("Excel文件已导出成功！");
            // 如果你在WPF中，可以替换Console.WriteLine为MessageBox.Show或其他UI相关的通知方式  
        }

     

        private async void SearchButton_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                await SearchAsync();
            }
        }
    }


}
